<?php
/**
 * Galdic project
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Galdic
 * @package    Galdic_Model_DbTable
 * @copyright  Copyright (c) 2009 vifito (http://vifito.eu)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Admin_Model_DbTable_Definitions
 * 
 * @package    Galdic_Model_DbTable
 * @copyright  Copyright (c) 2009 vifito (http://vifito.eu)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Definitions.php 1 2009-09-10 10:42:56Z vifito $
 */
class Admin_Model_DbTable_Definitions extends Zend_Db_Table
{
	protected $_name = "definitions";
	protected $_id   = "id";
    protected $_referenceMap = array(
        'Term' => array(
            'columns' => array('term_id'),
            'refTableClass' => 'Admin_Model_DbTable_Terms',
            'refColumns' => array('id')
        ),
        'Category' => array(
            'columns' => array('category_id'),
            'refTableClass' => 'Admin_Model_DbTable_Categories',
            'refColumns' => array('id')
        ),
    );
    
    
    public function fromJson($json, $term_id)
    {
        $this->clearDefinitions($term_id);
        
        $definitions = json_decode($json);
        
        if(is_array($definitions)) {
            foreach($definitions as $definition) {
                $data = array();
                
                $data['content']     = $definition->content;
                $data['etymology']   = $definition->etymology;
                $data['category_id'] = $definition->category_id;
                $data['term_id']     = $term_id;
                
                $data['created'] = date('Y-m-d H:i:s');
                $data['updated'] = date('Y-m-d H:i:s');
                
                $this->insert($data);                
            }
        }
    }
    
    public function toJson($term_id)
    {
        $json_definitions = array();
        
        // TODO: review SQL injection
        $rows = $this->fetchAll('term_id='.$term_id, 'id ASC');
        foreach($rows as $row) {
            $obj = new stdClass();
            $obj->category_id = $row->category_id;
            $obj->etymology   = $row->etymology;
            $obj->content     = $row->content;
            
            $json_definitions[] = $obj;
        }
        
        return json_encode($json_definitions);
    }
    
    public function clearDefinitions($term_id)
    {
        $this->delete('term_id=' . intval($term_id));
    }
}
